﻿using DevExpress.XtraEditors;
using DevExpress.XtraPrinting.Native.WebClientUIControl;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinForm_Mes.ProductManagement.BaseSetting;

namespace WinForm_Mes.ProductManagement
{
    public partial class BaseSet : DevExpress.XtraEditors.XtraForm
    {
        private string baseUrl = "http://localhost:5204";
        private HttpClient httpClient;
        public BaseSet()
        {
            InitializeComponent();
            this.Text = "计量单位";
            httpClient = new HttpClient();
            InitializeEvents();
        }
        //绑定按钮事件
        private void InitializeEvents()
        {
            //添加按钮点击事件
            checkButton1.CheckedChanged +=AddButton;
            //查询按钮点击事件
            simpleButton1.Click += SearchButton;
            // 删除按钮点击事件
            simpleButton3.Click += DeleteButton;
        }
        private void BaseSet_Load(object sender, EventArgs e)
        {
            LoadUnitData();
        }
        private async void LoadUnitData()
        {
            try
            {
                // 显示提示信息
                gridControl1.DataSource = null;
                // 调用后端API获取数据
                HttpResponseMessage response = await httpClient.GetAsync(baseUrl + "/api/Units/GetAllUnits");

                if (response.IsSuccessStatusCode)
                {
                    string jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonConvert.DeserializeObject<ApiResponse<UnitsModel>>(jsonContent);
                    var units = apiResponse.items;

                    // 绑定数据到表格
                    gridControl1.DataSource = units;

                    // 设置列映射
                    gridView1.Columns["id"].Visible = false;
                    gridView1.Columns["unitsCode"].Caption = "单位编码";
                    gridView1.Columns["unitsName"].Caption = "单位名称";
                    gridView1.Columns["isUnits"].Caption = "是否主单位";
                    gridView1.Columns["unitsRatio"].Caption = "与主单位换算比例";
                    gridView1.Columns["isUsing"].Caption = "是否启用";
                    gridView1.Columns["remark"].Caption = "备注";
                }
                else
                {
                    MessageBox.Show("获取计量单位数据失败！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("发生错误：" + ex.Message);
            }
        }
        //查询按钮点击事件
        private async void SearchButton(object sender, EventArgs e)
        {
            try
            {
                string unitsCode = textEdit1.Text.Trim();
                string unitsName = textEdit2.Text.Trim();

                // 构建查询参数
                string queryParams = "?";
                if (!string.IsNullOrEmpty(unitsCode))
                {
                    queryParams += $"unitsCode={unitsCode}&";
                }
                if (!string.IsNullOrEmpty(unitsName))
                {
                    queryParams += $"unitsName={unitsName}&";
                }

                // 去掉最后一个 & 号
                if (queryParams.EndsWith("&"))
                {
                    queryParams = queryParams.Substring(0, queryParams.Length - 1);
                }

                // 如果只有问号则不附加参数
                if (queryParams == "?")
                {
                    queryParams = "";
                }

                HttpResponseMessage response = await httpClient.GetAsync(baseUrl + "/api/Units/GetAllUnits" + queryParams);

                if (response.IsSuccessStatusCode)
                {
                    string jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonConvert.DeserializeObject<ApiResponse<UnitsModel>>(jsonContent);
                    var units = apiResponse.items;

                    // 绑定数据到表格
                    gridControl1.DataSource = units;
                }
                else
                {
                    MessageBox.Show("查询计量单位数据失败！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询发生错误：" + ex.Message);
            }
        }

        //添加按钮点击事件
        private void AddButton(object sender, EventArgs e)
        {
            AddBaseSettingForm addForm= new AddBaseSettingForm();
            addForm.ShowDialog();
            LoadUnitData();
        }
        
        //删除按钮点击事件
        private void DeleteButton(object sender, EventArgs e)
        {
            // 获取当前选中行的ID
            if (gridView1.GetSelectedRows().Length == 0)
            {
                XtraMessageBox.Show("请先选择要删除的记录");
                return;
            }

            int rowHandle = gridView1.GetSelectedRows()[0];
            if (rowHandle >= 0)
            {
                long id = Convert.ToInt64(gridView1.GetRowCellValue(rowHandle, "id"));
                DeleteUnit(id);
            }
        }
        /// <summary>
        /// 删除选中的单位
        /// </summary>
        /// <param name="id">要删除的单位ID</param>
        private async void DeleteUnit(long id)
        {
            try
            {
                if (XtraMessageBox.Show("确定要删除此单位吗？", "确认删除",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                {
                    return;
                }

                // 发送删除请求
                HttpResponseMessage response = await httpClient.DeleteAsync($"{baseUrl}/api/Units/LoginDel{id}");

                if (response.IsSuccessStatusCode)
                {
                    XtraMessageBox.Show("删除成功！");
                    // 如果在BaseSet窗体中，刷新数据
                    LoadUnitData();
                }
                else
                {
                    string errorContent = await response.Content.ReadAsStringAsync();
                    XtraMessageBox.Show($"删除失败：{response.StatusCode}\n{errorContent}");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"操作出错：{ex.Message}");
            }
        }






        // 在你的前端项目中添加这个类（可以放在单独的Models文件夹中）
        public class UnitsModel
        {
            /// <summary>
            /// 主键Id
            /// </summary>
            public long id { get; set; }
            /// <summary>
            /// 单位编码
            /// </summary>
            public string unitsCode { get; set; }
            /// <summary>
            /// 单位名称
            /// </summary>
            public string unitsName { get; set; }
            /// <summary>
            /// 是否是主单位
            /// </summary>
            public bool isUnits { get; set; }
            /// <summary>
            ///与主单位换算比例
            /// </summary>
            public int unitsRatio { get; set; }
            /// <summary>
            /// 是否启用
            /// </summary>
            public bool isUsing { get; set; }
            /// <summary>
            /// 备注
            /// </summary>
            public string remark { get; set; }
            public string CreateUserId { get; set; } = "admin";
            public string UpdateUserId { get; set; } = "admin";
        }
        // 创建一个包装类
        public class ApiResponse<T>
        {
            public int total { get; set; } = 0;
            public int pageIndex { get; set; } = 1;
            public int pageSize { get; set; } = 10;
            public List<T> items { get; set; } = new List<T>();
            // 其他可能的属性...
        }
    }
}